package me.jiatao.jetpack

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main1() = runBlocking<Unit> {

    val flowData = (1..10).asFlow().map {
        delay(200)
        println("map")
        it
    }.shareIn(
        scope = GlobalScope,
        started = SharingStarted.Eagerly,
        replay = 5
    )


    //用于显示程序运行
    launch {
        while (true) {
            delay(200)
            println("after  200ms")
        }
    }


    launch {
        delay(3000)
        println("flow collect before")
        flowData.collect {
            println("collect it ---> $it")
        }
    }

//    launch {
//        withTimeout(5000) {
//            while (true) {
//                delay(100)
//                println("average--->" + flowData.replayCache)
//            }
//        }
//    }

//    launch {
//      val flow2 =  flowData.onSubscription {
//            (100..110).forEach {
//                delay(100)
//                emit(it)
//            }
//        }
//
//        flow2.collect{
//            println("flow2 ---> $it")
//        }
//    }


    delay(20000)
}


fun main() = runBlocking {

    val mutableSharedFlow =
        MutableSharedFlow<Int>(replay = 5, extraBufferCapacity =3)

    launch {
        (1..30).forEach {
            delay(100)
            println("emit $it")
            mutableSharedFlow.emit(it)
        }
    }

    mutableSharedFlow.collect {
        delay(1500)
        println("collect--->$it")
    }
}